"""
侧边栏组件 - 基于PySide6实现
支持折叠/展开、图标+文本显示、悬停效果
"""
from PySide6.QtWidgets import (
    QWidget, QVBoxLayout, QHBoxLayout, QPushButton, 
    QLabel, QFrame, QScrollArea, QSizePolicy
)
from PySide6.QtCore import Qt, Signal, QPropertyAnimation, QEasingCurve, QSize
from PySide6.QtGui import QIcon, QPainter, QColor


class SidebarButton(QPushButton):
    """侧边栏按钮组件"""
    
    def __init__(self, text, icon=None, parent=None):
        super().__init__(parent)
        self.setText(text)
        if icon:
            self.setIcon(icon)
        
        self.setCheckable(True)
        self.setMinimumHeight(40)
        self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
        
        # 设置样式
        self.setStyleSheet("""
            QPushButton {
                text-align: left;
                padding: 10px 15px;
                border: none;
                background-color: transparent;
                color: #333;
                font-size: 14px;
            }
            QPushButton:hover {
                background-color: #e0e0e0;
            }
            QPushButton:checked {
                background-color: #d0d0d0;
                border-left: 3px solid #0078d4;
            }
        """)


class SidebarSection(QFrame):
    """侧边栏分组"""
    
    def __init__(self, title, parent=None):
        super().__init__(parent)
        self.title = title
        self.buttons = []
        
        self.setFrameShape(QFrame.Shape.StyledPanel)
        self.setStyleSheet("""
            QFrame {
                background-color: #f5f5f5;
                border: none;
            }
        """)
        
        # 主布局
        self.main_layout = QVBoxLayout(self)
        self.main_layout.setContentsMargins(0, 0, 0, 0)
        self.main_layout.setSpacing(0)
        
        # 标题栏
        self.title_widget = QWidget()
        title_layout = QHBoxLayout(self.title_widget)
        title_layout.setContentsMargins(15, 8, 15, 8)
        
        self.title_label = QLabel(title)
        self.title_label.setStyleSheet("""
            QLabel {
                font-weight: bold;
                font-size: 12px;
                color: #666;
            }
        """)
        title_layout.addWidget(self.title_label)
        
        self.main_layout.addWidget(self.title_widget)
        
        # 按钮容器
        self.button_container = QWidget()
        self.button_layout = QVBoxLayout(self.button_container)
        self.button_layout.setContentsMargins(0, 0, 0, 0)
        self.button_layout.setSpacing(2)
        
        self.main_layout.addWidget(self.button_container)
    
    def add_button(self, text, icon=None):
        """添加按钮"""
        btn = SidebarButton(text, icon, self)
        self.buttons.append(btn)
        self.button_layout.addWidget(btn)
        return btn
    
    def add_separator(self):
        """添加分隔线"""
        separator = QFrame()
        separator.setFrameShape(QFrame.Shape.HLine)
        separator.setFrameShadow(QFrame.Shadow.Sunken)
        separator.setStyleSheet("background-color: #ddd;")
        separator.setMaximumHeight(1)
        self.button_layout.addWidget(separator)


class Sidebar(QFrame):
    """侧边栏主组件"""
    
    # 信号：当按钮被点击时发出
    button_clicked = Signal(str)  # 传递按钮文本
    
    def __init__(self, parent=None):
        super().__init__(parent)
        
        self.expanded_width = 200
        self.collapsed_width = 50
        self.is_expanded = True
        
        self.setFixedWidth(self.expanded_width)
        self.setFrameShape(QFrame.Shape.StyledPanel)
        self.setStyleSheet("""
            QFrame {
                background-color: #f5f5f5;
                border-right: 1px solid #ddd;
            }
        """)
        
        # 主布局
        main_layout = QVBoxLayout(self)
        main_layout.setContentsMargins(0, 0, 0, 0)
        main_layout.setSpacing(0)
        
        # 顶部工具栏（折叠按钮）
        toolbar = QWidget()
        toolbar_layout = QHBoxLayout(toolbar)
        toolbar_layout.setContentsMargins(5, 5, 5, 5)
        
        self.toggle_btn = QPushButton("☰")
        self.toggle_btn.setFixedSize(40, 40)
        self.toggle_btn.setStyleSheet("""
            QPushButton {
                border: none;
                background-color: transparent;
                font-size: 20px;
            }
            QPushButton:hover {
                background-color: #e0e0e0;
                border-radius: 5px;
            }
        """)
        self.toggle_btn.clicked.connect(self.toggle_sidebar)
        toolbar_layout.addWidget(self.toggle_btn)
        toolbar_layout.addStretch()
        
        main_layout.addWidget(toolbar)
        
        # 滚动区域
        scroll_area = QScrollArea()
        scroll_area.setWidgetResizable(True)
        scroll_area.setFrameShape(QFrame.Shape.NoFrame)
        scroll_area.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
        
        # 内容容器
        self.content_widget = QWidget()
        self.content_layout = QVBoxLayout(self.content_widget)
        self.content_layout.setContentsMargins(0, 0, 0, 0)
        self.content_layout.setSpacing(10)
        self.content_layout.addStretch()
        
        scroll_area.setWidget(self.content_widget)
        main_layout.addWidget(scroll_area)
        
        # 动画 - 同时控制最小和最大宽度
        self.animation = QPropertyAnimation(self, b"maximumWidth")
        self.animation.setDuration(300)
        self.animation.setEasingCurve(QEasingCurve.Type.InOutQuad)
        
        # 同步minimumWidth的动画
        self.animation.valueChanged.connect(lambda value: self.setMinimumWidth(value))
        
        self.sections = []
    
    def add_section(self, title):
        """添加一个分组"""
        section = SidebarSection(title, self)
        self.sections.append(section)
        # 在stretch之前插入
        self.content_layout.insertWidget(self.content_layout.count() - 1, section)
        return section
    
    def toggle_sidebar(self):
        """切换侧边栏展开/折叠状态"""
        if self.is_expanded:
            self.collapse()
        else:
            self.expand()
    
    def collapse(self):
        """折叠侧边栏"""
        self.animation.setStartValue(self.expanded_width)
        self.animation.setEndValue(self.collapsed_width)
        self.animation.start()
        self.is_expanded = False
        
        # 隐藏文本，只显示图标
        for section in self.sections:
            section.title_label.hide()
            for btn in section.buttons:
                btn.setText("")
    
    def expand(self):
        """展开侧边栏"""
        self.animation.setStartValue(self.collapsed_width)
        self.animation.setEndValue(self.expanded_width)
        self.animation.start()
        self.is_expanded = True
        
        # 恢复文本显示
        for section in self.sections:
            section.title_label.show()
    
    def connect_button(self, button, callback):
        """连接按钮点击事件"""
        button.clicked.connect(lambda: self.on_button_clicked(button, callback))
    
    def on_button_clicked(self, button, callback):
        """按钮点击处理"""
        # 取消其他按钮的选中状态
        for section in self.sections:
            for btn in section.buttons:
                if btn != button:
                    btn.setChecked(False)
        
        # 发出信号
        self.button_clicked.emit(button.text())
        
        # 执行回调
        if callback:
            callback()
